function vd(obj) {
    var out = "";
    if(obj && typeof(obj) == "object"){
        for (var i in obj) {
            out += i + ": " + obj[i] + "\n";
        }
    } else {
        out = obj;
    }
    alert(out);
}

function er(msg){
    alert ('error : ' + msg);
}

function isDigit(v){
    if (!isNaN(parseInt(v * 1)))
        return true;
        return false;
}

//визначення чи точка входить в область фігури
function isPointInFigure(point, figure){
    var joins = [].concat(figure['joins']);
    if (joins.length < 3) return false;
    
    var cx = joins[0][0]['x'];
    var cy = joins[0][0]['y'];
    
    var p_last_x = cx - point['x']
    var p_last_y = cy - point['y']
    
    var sum = 0;
    //joins.splice(0,1);
    var endFlag = false;
    while(!endFlag){
        endFlag = true;
        for( var key in joins ){
    		if (joins[key][0]['x'] == cx && joins[key][0]['y'] == cy){
                cx = joins[key][1]['x'];
                cy = joins[key][1]['y'];
                joins.splice(key,1);
                endFlag = false;
                break;
    		} else if (joins[key][1]['x'] == cx && joins[key][1]['y'] == cy){
                cx = joins[key][0]['x'];
                cy = joins[key][0]['y'];
                joins.splice(key,1);
                endFlag = false;
                break;
    		}
    	}
        if (endFlag == false){
            var p_cur_x = cx - point['x']
            var p_cur_y = cy - point['y']
            
            var del= p_last_x * p_cur_y - p_cur_x * p_last_y;
            var xy= p_cur_x * p_last_x + p_cur_y * p_last_y;
            
            sum +=  Math.atan((p_last_x * p_last_x + p_last_y * p_last_y - xy)/del)+
                    Math.atan((p_cur_x * p_cur_x + p_cur_y * p_cur_y - xy )/del);
            
            p_last_x = p_cur_x;
            p_last_y = p_cur_y;
        }
    }
    
    return Math.abs(sum)>0.01;
}

//визначення чи точка входить в область однієї з фігур
//повертає номер фігури / null
function isPointInFigures(point, figures){
    for (var key in figures){
        if (isPointInFigure(point, figures[key]) == true)
            return key;
    }
    return null;
}

/*пошук точки перетину прямих(відрізків) l1 з l2 (is_l1_segment - чи відрізок)*/
function calcIntersectionLines(l1, is_l1_segment, l2, is_l2_segment){
	var x11 = l1[0]['x'];
	var x12 = l1[1]['x'];
	var y11 = l1['0']['y'];
	var y12 = l1['1']['y'];
	var x21 = l2['0']['x'];
	var x22 = l2['1']['x'];
	var y21 = l2['0']['y'];
	var y22 = l2['1']['y'];
	
	var A1 = y11 - y12;
	var B1 = x12 - x11;
	var C1 = y11 * (x12 - x11) - x11 * (y12 - y11);
	
	var A2 = y21- y22;
	var B2 = x22 - x21;
	var C2 = y21 * (x22 - x21) - x21 * (y22 - y21);
	
	A1 =  parseFloat((A1 + A2).toFixed(3));
	B1 =  parseFloat((B1 + B2).toFixed(3));
	C1 =  parseFloat((C1 + C2).toFixed(3));
    
    var x;
    var y;
    
	if ((A1 == 0 && A2 == 0) || (B1 == 0 && B2 == 0)){
		return null;
	}
	if (A1 == 0){
		y = C1 / B1;
		x = (C2 - B2 * y) / A2;
	} else if (B1 == 0){
		x = C1 / A1;
		y = (C2 - A2 * x) / B2;
	} else {
		k = A2 / A1;
		
		B2 -= B1 * k;
		C2 -= C1 * k;
		
		y = Math.round(C2 / B2);
		x = Math.round((C1 - B1 * y) / A1);
	}
	
	var res = new Array();
	
	res['x'] = x;
	res['y'] = y;
	
	if ((is_l1_segment == true)&&
		(((x11 != x12) && ((x > x11 && x > x12) || (x < x11 && x < x12))) ||
		((y11 != y12) && ((y > y11 && y > y12) || (y < y11 && y < y12)))))
		return null;
	if ((is_l2_segment == true)&&
		(((x21 != x22) && ((x > x21 && x > x22) || (x < x21 && x < x22))) ||
		((y21 != y22) && ((y > y21 && y > y22) || (y < y21 && y < y22)))))
		return null;
	return res;
}

function calc_distance(p1, p2){
	return Math.sqrt(Math.pow(p1['x'] - p2['x'], 2) + Math.pow(p1['y'] - p2['y'], 2));
}

/* пошук точки, яка знаходиться на перпедникулярі до прямої p1 p2,
 * який проходить через точку p1, на відстані width_splitter / 2 від прямої*/
function calcLinesForSplitter(line, width_splitter){
	var x1 = line[0]['x'];
	var y1 = line[0]['y'];
	var x2 = line[1]['x'];
	var y2 = line[1]['y'];
	
	if (x1 == x2 && y1 == y2){
		return null;
	}
	
	var res = new Array();
    res[0] = new Array();
    res[0][0] = new Array();
    res[0][1] = new Array();
    res[1] = new Array();
    res[1][0] = new Array();
    res[1][1] = new Array();
    
    var L1 = width_splitter / 2;
	
	if (x1 == x2){
        res[0][0]['y'] = y1;
        res[1][0]['y'] = y1;
        res[0][1]['y'] = y2;
        res[1][1]['y'] = y2;
        
        res[0][0]['x'] = x1 - L1;
        res[0][1]['x'] = x1 - L1;
        res[1][0]['x'] = x2 + L1;
        res[1][1]['x'] = x2 + L1;
	} else if (y1 == y2){
		res[0][0]['x'] = x1;
        res[1][0]['x'] = x1;
        res[0][1]['x'] = x2;
        res[1][1]['x'] = x2;
        
        res[0][0]['y'] = y1 - L1;
        res[0][1]['y'] = y1 - L1;
        res[1][0]['y'] = y2 + L1;
        res[1][1]['y'] = y2 + L1;
	} else {
        var L = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
    
        var K11 = (-2 * x2 + 2 * x1) / (2 * y2 - 2 * y1);
        var K21 = (-2 * x1 + 2 * x2) / (2 * y1 - 2 * y2);
        
        var K12 = (Math.pow(L, 2) - Math.pow(x2, 2) - Math.pow(y2, 2) + Math.pow(x1, 2) + Math.pow(y1, 2)) / (-2 * y2 + 2 * y1);
        var K22 = (Math.pow(L, 2) - Math.pow(x1, 2) - Math.pow(y1, 2) + Math.pow(x2, 2) + Math.pow(y2, 2)) / (-2 * y1 + 2 * y2);
        
        var A1 = 1 + Math.pow(K11, 2);
        var A2 = 1 + Math.pow(K21, 2);
        
        var B1 = -2* x1 + 2 *K11 * K12 - 2 * y1 * K11;
        var B2 = -2* x2 + 2 *K21 * K22 - 2 * y2 * K21;
        
        var C1 = Math.pow(x1, 2) - 2 * y1 * K12 + Math.pow(y1, 2) - Math.pow(L1, 2) + Math.pow(K12, 2);
        var C2 = Math.pow(x2, 2) - 2 * y2 * K22 + Math.pow(y2, 2) - Math.pow(L1, 2) + Math.pow(K22, 2);
        
        var sqrt_D1 = Math.sqrt(Math.pow(B1, 2) - 4 * A1 * C1);
        var sqrt_D2 = Math.sqrt(Math.pow(B2, 2) - 4 * A2 * C2);
        
        res[1][1]['x'] = (- B1 + sqrt_D1) / (2 * A1);
        res[1][1]['y'] = K11 * res[1][1]['x'] + K12;
        
        res[0][1]['x'] = (- B1 - sqrt_D1) / (2 * A1);
        res[0][1]['y'] = K11 * res[0][1]['x'] + K12;
        
        res[1][0]['x'] = (- B2 + sqrt_D2) / (2 * A2);
        res[1][0]['y'] = K21 * res[1][0]['x'] + K22;
        
        res[0][0]['x'] = (- B2 - sqrt_D2) / (2 * A2);
        res[0][0]['y'] = K21 * res[0][0]['x'] + K22;
	}
    
    /*if (calc_distance(res[0][0], res[1][0]) > calc_distance(res[0][0], res[1][1])){
        var temp = res[1][0];
        res[1][0] = res[1][1];
        res[1][1] = temp;
    }*/
    
	return res;
}

/*Знак точки на прямій*/
function signPointInLine(line, point){
	var x1 = line[0]['x'];
	var x2 = line[1]['x'];
	var y1 = line[0]['y'];
	var y2 = line[1]['y'];
	
	var A = y2 - y1;
	var B = x2 - x1;
	var C = y1 * B - x1 * A;
	
	return (A * point['x'] - B * point['y'] + C) * (A < 0 ? -1 : 1);
}
//service

var wc = null;

var model = new Array();
var real = new Array();
var elementBorderColor = '#000000';

function addJoin(figures, numberFigure, x0, y0, x1, y1){
    if (numberFigure == null){
        numberFigure = figures.length;
    }
    if (figures[numberFigure] == null){
        figures[numberFigure] = new Array();
    }
    if(figures[numberFigure]['joins'] == null){
        figures[numberFigure]['joins'] = new Array();
    }
    var joins = figures[numberFigure]['joins'];
    var numberJoin = joins.length;
    if (figures[numberFigure]['joins'][numberJoin] == null){
        figures[numberFigure]['joins'][numberJoin] = new Array();
    }
    figures[numberFigure]['joins'][numberJoin][0] = new Array();
    figures[numberFigure]['joins'][numberJoin][1] = new Array();
    figures[numberFigure]['joins'][numberJoin][0]['x'] = x0;
    figures[numberFigure]['joins'][numberJoin][0]['y'] = y0;
    figures[numberFigure]['joins'][numberJoin][1]['x'] = x1;
    figures[numberFigure]['joins'][numberJoin][1]['y'] = y1;
    return numberFigure;
}

function addParams(figures, numberFigure, color, name){
    if (numberFigure == null){
        numberFigure = figures.length;
    }
    if (figures[numberFigure] == null){
        figures[numberFigure] = new Array();
    }
    if(figures[numberFigure]['params'] == null){
        figures[numberFigure]['params'] = new Array();
    }
    figures[numberFigure]['params']['color'] = color;
    figures[numberFigure]['params']['name'] = name;
    return numberFigure;
}

function drawFigure(scale, ctx, figure){
    var ctx = ctx;
    var joins = [].concat(figure['joins']);
    ctx.strokeStyle = elementBorderColor; // Цвет обводки
	ctx.lineWidth = 2; // Товщина линии
	ctx.fillStyle = figure['params']['color']; // Цвет заливки
	
	ctx.beginPath();
	ctx.moveTo(joins[0][0]['x'] * scale, joins[0][0]['y'] * scale);
    ctx.lineTo(joins[0][1]['x'] * scale, joins[0][1]['y'] * scale);
    var cx = joins[0][1]['x'];
    var cy = joins[0][1]['y'];
    joins.splice(0,1);
    var endFlag = false;
    while(!endFlag){
        endFlag = true;
        for( var key in joins ){
    		if (joins[key][0]['x'] == cx && joins[key][0]['y'] == cy){
                cx = joins[key][1]['x'];
                cy = joins[key][1]['y'];
                joins.splice(key,1);
                ctx.lineTo(cx * scale, cy * scale);
                endFlag = false;
                break;
    		} else if (joins[key][1]['x'] == cx && joins[key][1]['y'] == cy){
                cx = joins[key][0]['x'];
                cy = joins[key][0]['y'];
                joins.splice(key,1);
                ctx.lineTo(cx * scale, cy * scale);
                endFlag = false;
                break;
    		}
    	}
    }
	ctx.closePath();  
    ctx.fill();
    ctx.stroke();
}

function drawFigures(scale, figures, layout){
    var ctx = layout.getContext('2d');
    ctx.clearRect(0, 0, layout.width, layout.height);
    for(var key in figures){
        drawFigure(scale, ctx, figures[key]);
    }
}

//добавити карниз
function addCornice(real, model){
    real['system_figures'] = new Array();
    var figures = real['system_figures'];
    
    var numberFigure = addParams(figures, null, '#' + real['system_texture']['color'], 'cornice');
    addJoin(figures, numberFigure, 0, 0 , real['width'], 0);
    addJoin(figures, numberFigure, real['width'], 0, real['width'], real['cornice_width']);
    addJoin(figures, numberFigure, real['width'], real['cornice_width'], 0, real['cornice_width']);
    addJoin(figures, numberFigure, 0, real['cornice_width'], 0, 0);
}

//добавити поріг
function addThreshold(real, model){
    var figures = real['system_figures'];
    
    var numberFigure = addParams(figures, null, '#' + real['system_texture']['color'], 'treshold');
    addJoin(figures, numberFigure, 0, real['height'] - real['threshold_width'], real['width'], real['height'] - real['threshold_width']);
    addJoin(figures, numberFigure, real['width'], real['height'] - real['threshold_width'], real['width'], real['height']);
    addJoin(figures, numberFigure, real['width'], real['height'], 0, real['height']);
    addJoin(figures, numberFigure, 0, real['height'], 0, real['height'] - real['threshold_width']);
    
    drawFigures(model['scale'], figures, model['system_layout']);
}

//створення полотна для карниза та порога
function createSystemLayout(wc, real, model){
    var systemLayout = document.createElement('canvas');
    systemLayout.setAttribute('id', 'system_layout');
    systemLayout.width = real['width'] * model['scale'];
    systemLayout.height = real['height'] * model['scale'];
    
    $(systemLayout).css('position', 'absolute');
    $(systemLayout).css('z-index', '102');
    
    $(systemLayout).css('left', '50%');
    $(systemLayout).css('margin-left', (-1 * real['width'] * model['scale']) / 2);
    
    model['system_layout'] = systemLayout;
    wc.append(systemLayout);
    
    addCornice(real, model);
    addThreshold(real, model);
}

function addDoorHandlys(real, model, i){
    var real_door = real['doors']['doors'][i];
    var door_figures = real_door['system_figures'];
    
    numberFigure = addParams(door_figures, null, '#' + real['system_texture']['color'], 'handly_left');
    addJoin(door_figures, numberFigure, 0, real['top_indentation'] , real['handly_total_width'], real['top_indentation']);
    addJoin(door_figures, numberFigure, real['handly_total_width'], real['top_indentation'], real['handly_total_width'], real['doors']['height'] - real['bottom_indentation']);
    addJoin(door_figures, numberFigure, real['handly_total_width'], real['doors']['height'] - real['bottom_indentation'], 0, real['doors']['height'] - real['bottom_indentation']);
    addJoin(door_figures, numberFigure, 0, real['doors']['height'] - real['bottom_indentation'], 0, real['top_indentation']);
    
    numberFigure = addParams(door_figures, null, '#' + real['system_texture']['color'], 'handly_right');
    addJoin(door_figures, numberFigure, real['doors']['width'] - real['handly_total_width'], real['top_indentation'] , real['doors']['width'], real['top_indentation']);
    addJoin(door_figures, numberFigure, real['doors']['width'], real['top_indentation'], real['doors']['width'], real['doors']['height'] - real['bottom_indentation']);
    addJoin(door_figures, numberFigure, real['doors']['width'], real['doors']['height'] - real['bottom_indentation'], real['doors']['width'] - real['handly_total_width'], real['doors']['height'] - real['bottom_indentation']);
    addJoin(door_figures, numberFigure, real['doors']['width'] - real['handly_total_width'], real['doors']['height'] - real['bottom_indentation'], real['doors']['width'] - real['handly_total_width'], real['top_indentation']);
    
    drawFigures(model['scale'], door_figures, model['doors']['doors'][i]['system_layout']);
}

function addDoorIndentations(real, model, i){
    var real_door = real['doors']['doors'][i];
    
    real_door['system_figures'] = new Array();
    var door_figures = real_door['system_figures'];
    
    numberFigure = addParams(door_figures, null, '#' + real['system_texture']['color'], 'top_indentation');
    addJoin(door_figures, numberFigure, 0, 0 , real['doors']['width'], 0);
    addJoin(door_figures, numberFigure, real['doors']['width'], 0, real['doors']['width'], real['top_indentation']);
    addJoin(door_figures, numberFigure, real['doors']['width'], real['top_indentation'], 0, real['top_indentation']);
    addJoin(door_figures, numberFigure, 0, real['top_indentation'], 0, 0);
    
    numberFigure = addParams(door_figures, null, '#' + real['system_texture']['color'], 'bottom_indentation');
    addJoin(door_figures, numberFigure, 0, real['doors']['height'] - real['bottom_indentation'] , real['doors']['width'], real['doors']['height'] - real['bottom_indentation']);
    addJoin(door_figures, numberFigure, real['doors']['width'], real['doors']['height'] - real['bottom_indentation'], real['doors']['width'], real['doors']['height']);
    addJoin(door_figures, numberFigure, real['doors']['width'], real['doors']['height'], 0, real['doors']['height']);
    addJoin(door_figures, numberFigure, 0, real['doors']['height'], 0, real['doors']['height'] - real['bottom_indentation']);
}

//створення полотен для систем для кожної дверки
function createDoorSystemLayout(model, real, i){
    var current_door_system_canvas = document.createElement('canvas');
    current_door_system_canvas.setAttribute('id', 'door_system_' + i);
    current_door_system_canvas.width = real['doors']['width'] * model['scale'] + 2;
    current_door_system_canvas.height = real['doors']['height'] * model['scale'];
    
    $(current_door_system_canvas).css('position', 'absolute');
    $(current_door_system_canvas).css('left', 0);
    $(current_door_system_canvas).css('top', 0);
    $(current_door_system_canvas).css('z-index', 2);
    model['doors']['doors'][i]['system_layout'] = current_door_system_canvas;
    $(model['doors']['doors'][i]['wrapper']).append(current_door_system_canvas);
    addDoorIndentations(real, model, i);
    addDoorHandlys(real, model, i);
}

//Добавити стартовий кусок у заповнення по всій площі
function addStartFillFigure(model, real, i){
    real['doors']['doors'][i]['fill_figures'] = new Array();
    var fill_figures = real['doors']['doors'][i]['fill_figures'];
    
    //TODO: колір заглушка
    var numberFigure = addParams(fill_figures, null, '#0000ff', 'top_indentation');
    addJoin(fill_figures, numberFigure, 0, 0 , real['doors']['fill_width'], 0);
    addJoin(fill_figures, numberFigure, real['doors']['fill_width'], 0, real['doors']['fill_width'], real['doors']['fill_height']);
    addJoin(fill_figures, numberFigure, real['doors']['fill_width'], real['doors']['fill_height'], 0, real['doors']['fill_height']);
    addJoin(fill_figures, numberFigure, 0, real['doors']['fill_height'], 0, 0);
    
    drawFigures(model['scale'], fill_figures, model['doors']['doors'][i]['fill_layout']);
}

//створення полотен для заповнення для кожної дверки
//і стартового заповнення по всій площі
function createDoorFillLayout(model, real, i){
    var current_door_fill_canvas = document.createElement('canvas');
    current_door_fill_canvas.setAttribute('id', 'door_fill_' + i);
    current_door_fill_canvas.width = real['doors']['fill_width'] * model['scale'];
    current_door_fill_canvas.height = real['doors']['fill_height'] * model['scale'];
    
    $(current_door_fill_canvas).css('position', 'absolute');
    $(current_door_fill_canvas).css('left', real['doors']['fill_left_offset'] * model['scale']);
    $(current_door_fill_canvas).css('top', (real['doors']['fill_top_offset']) * model['scale']);
    $(current_door_fill_canvas).css('z-index', 1);
    
    model['doors']['doors'][i]['fill_layout'] = current_door_fill_canvas;
    $(model['doors']['doors'][i]['wrapper']).append(current_door_fill_canvas);
    addStartFillFigure(model, real, i);
}

//створення обгортки для кожної дверки
function createDoors(real, model){
    model['doors']['doors'] = new Array();
    real['doors']['doors'] = new Array();
    
    real['doors']['fill_top_offset'] = real['top_indentation'] - real['fill_capture'];
    real['doors']['fill_bottom_offset'] = real['bottom_indentation'] - real['fill_capture'];
    real['doors']['fill_left_offset'] = real['doors']['handly_spec']['base_width'] - real['doors']['handly_spec']['capture'];
    real['doors']['fill_width'] = real['doors']['width'] - real['doors']['fill_left_offset'] * 2;
    real['doors']['fill_height'] = real['doors']['height'] - real['doors']['fill_top_offset'] - real['doors']['fill_bottom_offset'];
    var left_offset = 0;
    var door_z_index = 0;
    for (i = 0; i < real['doors']['count_doors']; i++){
        var current_door_wrapper = document.createElement('div');
        current_door_wrapper.setAttribute('id', 'door_wrapper_' + i);
        $(current_door_wrapper).width(real['doors']['width'] * model['scale']);
        $(current_door_wrapper).height(real['doors']['height'] * model['scale']);
        $(current_door_wrapper).css('position', 'absolute');
        
        var doorsWrapper = model['doors']['doors_wrapper'];
        $(doorsWrapper).append(current_door_wrapper);
        if (i == 0){
            left_offset = 0;
            door_z_index = 0;
        } else if (i == 2 && real['doors']['doors_position'] == 2){
            left_offset += real['doors']['width'];
        } else {
            left_offset += real['doors']['width'] - real['doors']['handly_spec']['base_width'];
            door_z_index = (door_z_index + 1) % 2;
        }
        
        $(current_door_wrapper).css('z-index', door_z_index);
        $(current_door_wrapper).css('left', left_offset * model['scale'] + "px"); 
        $(current_door_wrapper).css('top', model['top_indentation'] + "px");
        model['doors']['doors'][i] = new Array();
        real['doors']['doors'][i] = new Array();
        model['doors']['doors'][i]['wrapper'] = current_door_wrapper;
        createDoorFillLayout(model, real, i);
        createDoorSystemLayout(model, real, i);
    }
}

//створення обгортки для всіх дверей
function createDoorsWrapper(wc, real, model){
    var doorsWrapper = document.createElement('div');
    doorsWrapper.setAttribute('id', 'doors_wrapper');
    
    var count_overlaps = real['doors']['count_doors'] - ((real['doors']['count_doors'] == 4 && real['doors']['doors_position'] == 2 ? 2 : 1));
    real['doors']['count_overlaps'] = count_overlaps;
    real['doors']['width'] = Math.floor((real['width'] + real['doors']['handly_spec'].base_width * count_overlaps) / real['doors']['count_doors']);
    real['doors']['height'] = real['height'] - real['top_door_offset'] - real['bottom_door_offset'];
    real['handly_total_width'] = real['doors']['handly_spec'].handle_width > real['doors']['handly_spec'].base_width ? real['doors']['handly_spec'].handle_width : real['doors']['handly_spec'].base_width;
    $(doorsWrapper).width(real['width'] * model['scale']);
    $(doorsWrapper).height(real['doors']['height'] * model['scale']);
    
    $(doorsWrapper).css('position', 'absolute');
    $(doorsWrapper).css('z-index', '101');
    $(doorsWrapper).css('left', '50%');
    $(doorsWrapper).css('margin-left', -1 * $(doorsWrapper).width() / 2);
    $(doorsWrapper).css('top', real['top_door_offset'] * model['scale']);
    $(doorsWrapper).css('white-space', 'nowrap');
    
    model['doors'] = new Array();
    model['doors']['doors_wrapper'] = doorsWrapper;
    wc.append(doorsWrapper);
    
    createDoors(real, model);
}

//коефіцієнт, на який множити реал, щоб отримати модель
function calc_scale(wall_hole_width, 
                    wall_hole_height, 
                    model_wall_hole_width, 
                    model_wall_hole_height){
	var coef_width = model_wall_hole_width / wall_hole_width;
	var coef_height = model_wall_hole_height / wall_hole_height;
	return (coef_width <= coef_height ? coef_width : coef_height);
}

/*побудова моделі*/
function create_model(wc, real, model){
    var wc_outer_width = wc.width() - 20;
    var wc_outer_height = wc_outer_width/2;
    //масштаб
    model['scale'] = calc_scale(real['width'], real['height'], wc_outer_width, wc_outer_height);
    //лівий відступ моделі
    model['margin_left'] = (wc_outer_width - real['width'] * model['scale']) / 2;
    wc_outer_height = real['height'] * model['scale'] + 1;
    wc.height(wc_outer_height);
    model['margin_top'] = (wc_outer_height - real['height'] * model['scale']) / 2;
    $.getJSON('calculator/showsystemparams/format/json', function(data) {
        for(var key in data){
            real[key] = data[key];
        }
        //створення дверей
        createDoorsWrapper(wc, real, model);
        createSystemLayout(wc, real, model);
        
        $('#buttons_service_panel #service_panel_group_main').show();
        for (var key in model['doors']['doors']){
            var current_door = model['doors']['doors'][key];
            
            var cur_down_fill_id = null;
            var down_point = null;
            var cur_down_fill_piece_id = null;
            //натиснута ліва кнопка миші на заповненні
            
            $(current_door['fill_layout']).live("mousedown", function(event){
                cur_down_fill_id = event['currentTarget']['id'].split('_');
                cur_down_fill_id = cur_down_fill_id[2];
                var figures = real['doors']['doors'][cur_down_fill_id]['fill_figures'];
                down_point = new Array();
                down_point['x'] = (event['offsetX']) / model['scale'];
                down_point['y'] = (event['offsetY']) / model['scale'];
                cur_down_fill_piece_id = isPointInFigures(down_point, figures);
            });
            
            //відпущена ліва кнопка миші на заповненні
            $(current_door['fill_layout']).live("mouseup", function(event){
                var cur_up_fill_id = event['currentTarget']['id'].split('_');
                cur_up_fill_id = cur_up_fill_id[cur_up_fill_id.length - 1];
                var figures = real['doors']['doors'][cur_up_fill_id]['fill_figures'];
                var up_point = new Array();
                up_point['x'] = (event['offsetX']) / model['scale'];
                up_point['y'] = (event['offsetY']) / model['scale'];
                
                var cur_up_fill_piece_id = isPointInFigures(up_point, figures);
                
                if (cur_down_fill_id != null && 
                    cur_up_fill_id != null && 
                    cur_down_fill_id == cur_up_fill_id &&
                    cur_down_fill_piece_id != null &&
                    cur_up_fill_piece_id != null &&
                    cur_down_fill_piece_id == cur_up_fill_piece_id)
                {
                    var figure = figures[cur_up_fill_piece_id];
                    var joins = [].concat(figure['joins']);
                    
                    var base_splitter_line = new Array();
                    
                    base_splitter_line[0] = down_point;
                    base_splitter_line[1] = up_point;
                    
                    //TODO: заглушка ширина сплітера
                    var split_lines = calcLinesForSplitter(base_splitter_line, real['base_width_splitter'] * model['scale']);
                    
                    var sign_in_figure_0 = signPointInLine(split_lines[0], split_lines[1][0]) * -1;
                    var sign_in_figure_1 = signPointInLine(split_lines[1], split_lines[0][0]) * -1;
                    
                    var new_figures = new Array();
                    
                    var numberFigure0 = addParams(new_figures, null, '#00ff00', 'fill_piece');
                    var numberFigure1 = addParams(new_figures, null, '#00ff00', 'fill_piece');
                    
                    var cx = joins[0][0]['x'];
                    var cy = joins[0][0]['y'];
                    
                    var cross_joins = new Array();
                    cross_joins[0] = new Array();
                    cross_joins[1] = new Array();
                    
                    var endFlag = false;
                    while(!endFlag){
                        endFlag = true;
                        for( var key in joins ){
                    		if (joins[key][0]['x'] == cx && joins[key][0]['y'] == cy){
                                cx = joins[key][1]['x'];
                                cy = joins[key][1]['y'];
                                endFlag = false;
                    		} else if (joins[key][1]['x'] == cx && joins[key][1]['y'] == cy){
                                cx = joins[key][0]['x'];
                                cy = joins[key][0]['y'];
                                endFlag = false;
                    		}
                            if (endFlag == false){
                                sign_p0_in_L0 = signPointInLine(split_lines[0], joins[key][0]);
                                sign_p1_in_L0 = signPointInLine(split_lines[0], joins[key][1]);
                                sign_p0_in_L1 = signPointInLine(split_lines[1], joins[key][0]);
                                sign_p1_in_L1 = signPointInLine(split_lines[1], joins[key][1]);
                                
                                if (sign_p0_in_L0 * sign_in_figure_0 > 0 && sign_p0_in_L1 * sign_in_figure_1 < 0){
                                // 0 in 0
                                    if (sign_p1_in_L0 * sign_in_figure_0 > 0 && sign_p1_in_L1 * sign_in_figure_1 < 0){
                                    //1 in 0
                                        addJoin(new_figures, numberFigure0, joins[key][0]['x'], joins[key][0]['y'], joins[key][1]['x'], joins[key][1]['y']);
                                    } else if (sign_p1_in_L0 * sign_in_figure_0 < 0 && sign_p1_in_L1 * sign_in_figure_1 > 0){
                                    //1 in 1
                                        var cross_point_0 = calcIntersectionLines(joins[key], true, split_lines[0], false);
                                        var cross_point_1 = calcIntersectionLines(joins[key], true, split_lines[1], false);
                                        cross_joins[0][cross_joins[0].length] = cross_point_0;
                                        cross_joins[1][cross_joins[1].length] = cross_point_1;
                                        addJoin(new_figures, numberFigure0, joins[key][0]['x'], joins[key][0]['y'], cross_point_0['x'], cross_point_0['y']);
                                        addJoin(new_figures, numberFigure1, joins[key][1]['x'], joins[key][1]['y'], cross_point_1['x'], cross_point_1['y']);
                                        
                                    } else if (sign_p1_in_L0 * sign_in_figure_0 < 0 && sign_p1_in_L1 * sign_in_figure_1 < 0){
                                    //1 no   
                                        var cross_point_0 = calcIntersectionLines(joins[key], true, split_lines[0], false);
                                        cross_joins[0][cross_joins[0].length] = cross_point_0;
                                        addJoin(new_figures, numberFigure0, joins[key][0]['x'], joins[key][0]['y'], cross_point_0['x'], cross_point_0['y']);
                                    }
                                    //-
                                } else if (sign_p0_in_L0 * sign_in_figure_0 < 0 && sign_p0_in_L1 * sign_in_figure_1 > 0){
                                    // 0 in 1
                                    if (sign_p1_in_L0 * sign_in_figure_0 > 0 && sign_p1_in_L1 * sign_in_figure_1 < 0){
                                        var cross_point_0 = calcIntersectionLines(joins[key], true, split_lines[0], false);
                                        var cross_point_1 = calcIntersectionLines(joins[key], true, split_lines[1], false);
                                        cross_joins[0][cross_joins[0].length] = cross_point_0;
                                        cross_joins[1][cross_joins[1].length] = cross_point_1;
                                        addJoin(new_figures, numberFigure0, joins[key][1]['x'], joins[key][1]['y'], cross_point_0['x'], cross_point_0['y']);
                                        addJoin(new_figures, numberFigure1, joins[key][0]['x'], joins[key][0]['y'], cross_point_1['x'], cross_point_1['y']);
                                    } else if (sign_p1_in_L0 * sign_in_figure_0 < 0 && sign_p1_in_L1 * sign_in_figure_1 > 0){
                                        addJoin(new_figures, numberFigure1, joins[key][0]['x'], joins[key][0]['y'], joins[key][1]['x'], joins[key][1]['y']);
                                    } else if (sign_p1_in_L0 * sign_in_figure_0 < 0 && sign_p1_in_L1 * sign_in_figure_1 < 0){
                                        var cross_point_1 = calcIntersectionLines(joins[key], true, split_lines[1], false);
                                        cross_joins[1][cross_joins[1].length] = cross_point_1;
                                        addJoin(new_figures, numberFigure1, joins[key][0]['x'], joins[key][0]['y'], cross_point_0['x'], cross_point_0['y']);
                                    }
                                    //-
                                } else if (sign_p0_in_L0 * sign_in_figure_0 < 0 && sign_p0_in_L1 * sign_in_figure_1 < 0){
                                    // 0 no
                                    if (sign_p1_in_L0 * sign_in_figure_0 > 0 && sign_p1_in_L1 * sign_in_figure_1 < 0){
                                        var cross_point_0 = calcIntersectionLines(joins[key], true, split_lines[0], false);
                                        cross_joins[0][cross_joins[0].length] = cross_point_0;
                                        addJoin(new_figures, numberFigure0, joins[key][1]['x'], joins[key][1]['y'], cross_point_0['x'], cross_point_0['y']);
                                    } else if (sign_p1_in_L0 * sign_in_figure_0 < 0 && sign_p1_in_L1 * sign_in_figure_1 > 0){
                                        var cross_point_1 = calcIntersectionLines(joins[key], true, split_lines[1], false);
                                        cross_joins[1][cross_joins[1].length] = cross_point_1;
                                        addJoin(new_figures, numberFigure1, joins[key][1]['x'], joins[key][1]['y'], cross_point_1['x'], cross_point_1['y']);
                                    }
                                }
                                
                                joins.splice(key,1);
                                break;
                            }
                    	}
                    }
                    
                    if (cross_joins[0].length == 2 && cross_joins[1].length == 2){
                        addJoin(new_figures, numberFigure0, cross_joins[0][0]['x'], cross_joins[0][0]['y'], cross_joins[0][1]['x'], cross_joins[0][1]['y']);
                        addJoin(new_figures, numberFigure1, cross_joins[1][0]['x'], cross_joins[1][0]['y'], cross_joins[1][1]['x'], cross_joins[1][1]['y']);
                        
                        figures.splice(cur_up_fill_piece_id,1);
                        real['doors']['doors'][cur_up_fill_id]['fill_figures'] = figures.concat(new_figures);
                        
                        drawFigures(model['scale'], real['doors']['doors'][cur_up_fill_id]['fill_figures'], model['doors']['doors'][cur_down_fill_id]['fill_layout']);
                        
                    } else {
                        figures = null;
                    }
                    
                    //TODO: last 
                }
            });
            
            $(current_door['fill_layout']).live("mousemove", function(event){
                
            });
        }
        
        $('#buttons_service_panel #service_panel_group_main #panel_button_edit').live("click", function(){
            $('#buttons_service_panel #service_panel_group_main').hide();
            $('#buttons_service_panel #service_panel_group_edit').show();
            $(model['doors']['doors_wrapper']).css('z-index', '103');
            for (var key in model['doors']['doors']){
                var current_door = model['doors']['doors'][key];
                $(current_door['fill_layout']).css('z-index', 3);
            }
            $('#buttons_service_panel #service_panel_group_edit #panel_button_apply').live("click", function(){
                $('#buttons_service_panel #service_panel_group_main').show();
                $('#buttons_service_panel #service_panel_group_edit').hide();
                for (var key in model['doors']['doors']){
                    var current_door = model['doors']['doors'][key];
                    $(current_door['fill_layout']).die();
                    $(current_door['fill_layout']).css('z-index', 1);
                }
                $(model['doors']['doors_wrapper']).css('z-index', '101');
            });
        });
    });
}

/*колір системи*/
function dialog_texture(form_create_wall_hole, real, model){
    $.getJSON('calculator/showsystemcolors/format/json', function(data) {
        var path = data.path_textures;
        var c2 = '';
        $.each(data.system_textures, function(key, val) {
            c2 += '<li id = select_item-' + key + '>';           
                c2 += '<div class="probe_texture" style="background-color: #' + val.color + '"></div>';
                c2 += '<div class="name_item">' + val.name + '</div>'; 
            c2 += '</li>';
        });
        var c = "";
    	c += "<div class='dialog_header'>Колір системи</div>";
        c += "<ul class='select_list' id='dialog_select_texture'>";
            if (c2 != ""){
                c = c.concat(c2);
            } else {
                c += "<div class='dialog_error'>Систем нема !</div>";
            }
        c += "</ul>";
    	$(form_create_wall_hole).html(c);
        var texture_id = null;
        $('#dialog_select_texture').selectable({
            selected: function(event, ui) {
                var number_texture = $(ui.selected).attr('id');
                number_texture = number_texture.split('-')[1];
                if (typeof number_texture !== 'undefined' &&
                    data.system_textures[number_texture] != null)
                {
                    real['system_texture'] = data.system_textures[number_texture];
                    wc.empty();
                    create_model(wc, real, model);
                }
            }
        });
    });
}

/*тип ручки*/
function dialog_type_handly(form_create_wall_hole, real, model){
    $.getJSON('calculator/showhandlytypes/format/json', function(data) {
        var path = data.path_handly_specs;
        var c2 = '';
        $.each(data.handly_types, function(key, val) {
            c2 += '<li id="select_item-' + key + '">';           
                c2 += "<img src='" + path + val.file_name +"'>";
                c2 += "<div class='name_item'>" + val.name + "</div>";
            c2 += '</li>';
        });
        var c = "";
        c += "<div class='dialog_header'>Ручки</div>";
        
            if (c2 != ""){
                c += "<ul class='select_list' id='dialog_select_handly_type'>";
                    c = c.concat(c2);
                c += "</ul>";
            } else {
                c += "<div class='dialog_data'>";
                    c += "<div class='dialog_error'>Ручок нема !</div>";
                c += "</div>";
            }
    	$(form_create_wall_hole).html(c);
        
        $('#dialog_select_handly_type').selectable({
            selected: function(event, ui) {
                var number_type_handly = $(ui.selected).attr('id');
                number_type_handly = number_type_handly.split('-')[1];
                if (typeof number_type_handly !== 'undefined' &&
                    data.handly_types[number_type_handly] != null)
                {
                    real['doors']['handly_spec'] = data.handly_types[number_type_handly];
                    $(form_create_wall_hole).empty();
                    dialog_texture(form_create_wall_hole, real, model);
                }
            }
        });
    });
}

/*кількість дверей*/
function dialog_count_doors(form_create_wall_hole, real, model){
	var c = "";
    c += "<div class='dialog_header'>Двері</div>";
    c += "<div class='dialog_data'>";
        c += "<table>";
            c += "<tr>";
                c += "<td>";
                    c += "<div class='dialog_lable'>Кількість дверей :</div>";
                c += "</td>";
                c += "<td>";
                    c += "<div class='dialog_value'>";
                        c += "<select name='menu' id='input_count_doors' size='1'>";
                			c += "<option selected='selected' value='2'>2</option>";
                			for (i = 3; i<=10; i++){
                				c += "<option value='" + i + "'>" + i + "</option>";
                			}
                		c += "</select>";
                    c += "</div>";
                c += "</td>";
            c += "</tr>";
            c += "<tr id='select_door_position'>";
                c += "<td colspan='2'>";
                    c += "<table>";
                        c += "<tr>";
                            c += "<td>";
                                c += "<div  class='dialog_group_header'>";
                                    c += "Положення дверей";
                                c += "</div>"
                            c += "</td>";
                        c += "</tr>";
                        c += "<tr>";
                            
                            c += "<td>";
                                c += "<ul class='select_list' id='dialog_select_position'>";
                                    c += '<li id="select_item-1">';           
                                        c += "<img src='img/door_position_1.png'>"
                                        c += '<div class="name_item">Шахматка</div>';
                                    c += '</li>';
                                    c += '<li id="select_item-2">';           
                                        c += "<img src='img/door_position_2.png'>";
                                        c += '<div class="name_item">Симетрія</div>';
                                    c += '</li>';
                                c += "</ul>";
                            c += "</td>";
                        c += "</tr>";
                    c += "</table>";
                c += "</td>";
            c += "</tr>";
        c += "</table>";
    c += "<div class='dialog_header dialog_buttons'>";
		c += "<div class='dialog_button' id='button_create_wall_hole_ok'";
		c += ">наступний</div>";
	c += "</div>";
    $(form_create_wall_hole).html(c);
    
    var number_type_door_position = null;
    $('#dialog_select_position').selectable({
        selected: function(event, ui) {
            number_type_door_position = $(ui.selected).attr('id');
            number_type_door_position = (number_type_door_position + "").split('-')[1];
        }
    });
    $('#input_count_doors').change(function(){
        if ($('#input_count_doors').val() == 4){
            $('#select_door_position').show();
        } else {
            $('#select_door_position').hide();
        }
    });
    $('#button_create_wall_hole_ok').click(function(){
        var count_doors = $('#input_count_doors').val();
        if (count_doors == 4 && 
            typeof number_type_door_position === 'undefined')
        {
            alert('Виберіть розташування дверей !');
            return; 
        }
        if (real['doors'] == null)
            real['doors'] = new Array();
        real['doors']['count_doors'] = count_doors;
        if (typeof number_type_door_position !== 'undefined'){
            real['doors']['doors_position'] = number_type_door_position;
        }  
        $(form_create_wall_hole).empty();
        dialog_type_handly(form_create_wall_hole, real, model);
    });
}

/*ширина, висота*/
function start_dialogs(wc, real, model){
    var form_create_wall_hole = document.createElement('div');
    form_create_wall_hole.setAttribute('class', 'dialog');
	var c = "";
	c += "<div class='dialog_header'>Дверний пройом</div>";
    c += "<div class='dialog_data'>";
        c += "<table>";
            c += "<tr>";
                c += "<td>";
        		  c += "<div class='dialog_lable'>Ширина пройому (мм) [ не менша 100 мм] :</div>";
        		c += "</td>";
                c += "<td>";
                    c += "<div class='dialog_value'>";
            			c += "<input class='text' id='input_wall_hole_width' value='3000' type='text'>";
            		c+= "</div>";
                c += "</td>";
        	c += "</tr>";
            c += "<tr>";
                c += "<td>";
        		  c += "<div class='dialog_lable'>Висота пройому (мм) [ не менша 100 мм] :</div>";
                c += "</td>";
                c += "<td>";
            		c += "<div class='dialog_value'>";
            			c += "<input class='text' id='input_wall_hole_height' value='1800' type='text'>";
            		c += "</div>";
                c += "</td>";
            c += "</tr>";
        c += "</table>";
    c += "</div>";
	c += "<div class='dialog_header dialog_buttons'>";
		c += "<div class='dialog_button' id='button_create_wall_hole_ok'";
		c += ">наступний</div>";
	c += "</div>"
	form_create_wall_hole.innerHTML = c;
    wc.append(form_create_wall_hole);
    $('#button_create_wall_hole_ok').click(function(){
        var wall_hole_width = Math.floor($('#input_wall_hole_width').val());
        var wall_hole_height = Math.floor($('#input_wall_hole_height').val());
        if (wall_hole_width > 100 && 
            wall_hole_height > 100)
        {
            real['width'] = wall_hole_width;
            real['height'] = wall_hole_height;
            $(form_create_wall_hole).empty();
            dialog_count_doors(form_create_wall_hole, real, model);
        } else {
            alert('Ширина і висота має бути не меншою 100 мм !');
        }
    });
}

function start(wc, real, model){
    start_dialogs(wc, real, model);
};

$(function(){
    wc = $('#wrapper_calculator');
    if (wc != null && wc.length > 0){
        start(wc, real, model);
    }
});